package com.mrzhou.auth.authorzation.impl;

import com.mrzhou.auth.authorzation.AbstractIntegrationAuthentication;
import com.mrzhou.auth.exception.IntegrationException;
import com.mrzhou.auth.service.CloudUserDetails;
import com.mrzhou.auth.support.IntegrationAuthenticationEntity;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.common.entity.system.UserInfo;
import com.mrzhou.common.feign.client.IUserClient;
import com.mrzhou.core.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

/**
 * 用户名密码登录
 */
@Component
@Primary
@Slf4j
public class UsernamePasswordAuthentication extends AbstractIntegrationAuthentication {

    @Autowired
    private IUserClient userClient;

    @Override
    public CloudUserDetails authentication(IntegrationAuthenticationEntity authEntity) throws IntegrationException {
        R<UserInfo> result = userClient.userInfo(authEntity.getUsername());
        if(!result.isSuccess()) {
            throw new IntegrationException(result.getMsg());
        }
        return CloudUserDetails.createCloudUserDetails(result.getData());
    }

    @Override
    public void prepare(IntegrationAuthenticationEntity authEntity) throws IntegrationException {

    }

    /**
     * 设置一些默认的处理
     * @param authEntity
     * @return
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity authEntity) {
        return TokenUtil.AUTH_REFRESH_TOKEN.equals(authEntity.getAuthType())
                ||TokenUtil.AUTH_PASSWORD.equalsIgnoreCase(authEntity.getAuthType())
                || TokenUtil.AUTH_PSW.equalsIgnoreCase(authEntity.getAuthType());
    }

}
